﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.DataType;
using FBroSharp.Lib;
using FBroSharp.Value;

namespace 多标签页浏览器
{
    public partial class Form1 : Form
    {
        // 标签页计数器，用于生成唯一的user_flag
        private int _tabCounter = 0;
        
        // 标签页到浏览器user_flag的映射
        private Dictionary<TabPage, string> _tabToUserFlag = new Dictionary<TabPage, string>();

        public Form1()
        {
            InitializeComponent();
            
            // 注意：不在构造函数中创建浏览器，因为此时 Panel 尺寸还未确定
            // 将在 Form_Load 事件中创建第一个标签页
        }

        /// <summary>
        /// 窗体加载完成事件
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {
            // 窗体加载完成后创建第一个标签页，此时 Panel 尺寸已确定
            CreateNewTab("https://www.baidu.com");
        }

        /// <summary>
        /// 创建新标签页
        /// </summary>
        private void CreateNewTab(string url = "https://www.baidu.com")
        {
            try
            {
                // 生成唯一的user_flag
                _tabCounter++;
                string userFlag = $"tab_browser_{_tabCounter}";

                // 创建标签页
                TabPage tabPage = new TabPage($"新标签页 {_tabCounter}");
                tabPage.Tag = userFlag;

                // 创建Panel作为浏览器容器
                Panel browserPanel = new Panel
                {
                    Name = $"panelBrowser_{_tabCounter}",
                    Dock = DockStyle.Fill
                };
                tabPage.Controls.Add(browserPanel);

                // 添加到TabControl
                tabControl1.TabPages.Add(tabPage);
                tabControl1.SelectedTab = tabPage;

                // 保存映射关系
                _tabToUserFlag[tabPage] = userFlag;

                // 创建浏览器窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = browserPanel.Handle,  // ⚠️ CRITICAL: 嵌入到Panel
                    x = 0,
                    y = 0,
                    width = browserPanel.Width,
                    height = browserPanel.Height,
                    window_name = $"浏览器标签页 {_tabCounter}"
                };

                // 创建浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this, tabPage);

                // 创建浏览器（使用default而不是null for event_control）
                bool success = FBroSharpControl.CreatBrowser(
                    url,
                    windowInfo,
                    settings,
                    null,  // request_context
                    null,  // extra_info
                    browserEvent,
                    default,  // ⚠️ CRITICAL: event_control 使用 default，不是 null!
                    userFlag
                );

                if (success)
                {
                    Console.WriteLine($"✅ 标签页 {_tabCounter} 创建成功，user_flag: {userFlag}");
                }
                else
                {
                    MessageBox.Show($"标签页 {_tabCounter} 创建失败！", "错误", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建标签页失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 关闭标签页
        /// </summary>
        private void CloseTab(TabPage tabPage)
        {
            try
            {
                if (_tabToUserFlag.ContainsKey(tabPage))
                {
                    string userFlag = _tabToUserFlag[tabPage];
                    
                    // 获取浏览器实例
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    if (browser != null && browser.IsValid)
                    {
                        // 关闭浏览器
                        browser.CloseBrowser(true, true);
                    }

                    // 移除映射
                    _tabToUserFlag.Remove(tabPage);
                }

                // 移除标签页
                tabControl1.TabPages.Remove(tabPage);

                // 如果没有标签页了，创建一个新的
                if (tabControl1.TabPages.Count == 0)
                {
                    CreateNewTab();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"关闭标签页失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 在当前标签页导航到URL
        /// </summary>
        private void NavigateToUrl(string url)
        {
            try
            {
                TabPage currentTab = tabControl1.SelectedTab;
                if (currentTab != null && _tabToUserFlag.ContainsKey(currentTab))
                {
                    string userFlag = _tabToUserFlag[currentTab];
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    
                    if (browser != null && browser.IsValid)
                    {
                        var mainFrame = browser.GetMainFrame();
                        if (mainFrame != null)
                        {
                            // 确保URL格式正确
                            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                            {
                                url = "https://" + url;
                            }
                            
                            mainFrame.LoadURL(url);
                            Console.WriteLine($"导航到: {url}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新当前标签页
        /// </summary>
        private void RefreshCurrentTab()
        {
            try
            {
                TabPage currentTab = tabControl1.SelectedTab;
                if (currentTab != null && _tabToUserFlag.ContainsKey(currentTab))
                {
                    string userFlag = _tabToUserFlag[currentTab];
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    
                    if (browser != null && browser.IsValid)
                    {
                        browser.Reload();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 后退
        /// </summary>
        private void GoBack()
        {
            try
            {
                TabPage currentTab = tabControl1.SelectedTab;
                if (currentTab != null && _tabToUserFlag.ContainsKey(currentTab))
                {
                    string userFlag = _tabToUserFlag[currentTab];
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    
                    if (browser != null && browser.IsValid)
                    {
                        browser.GoBack();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"后退失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 前进
        /// </summary>
        private void GoForward()
        {
            try
            {
                TabPage currentTab = tabControl1.SelectedTab;
                if (currentTab != null && _tabToUserFlag.ContainsKey(currentTab))
                {
                    string userFlag = _tabToUserFlag[currentTab];
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    
                    if (browser != null && browser.IsValid)
                    {
                        browser.GoForward();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"前进失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser(TabPage tabPage)
        {
            try
            {
                if (_tabToUserFlag.ContainsKey(tabPage))
                {
                    string userFlag = _tabToUserFlag[tabPage];
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    
                    if (browser != null && browser.IsValid)
                    {
                        // 获取Panel
                        Panel browserPanel = tabPage.Controls[0] as Panel;
                        if (browserPanel != null)
                        {
                            browser.MoveWindow(0, 0, browserPanel.Width, browserPanel.Height, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        #region 事件回调方法（从BrowserEvent调用）

        /// <summary>
        /// 浏览器创建完成回调
        /// </summary>
        public void OnBrowserCreated(IFBroSharpBrowser browser, TabPage tabPage)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnBrowserCreated(browser, tabPage)));
                return;
            }

            Console.WriteLine($"✅ 浏览器实例已创建: ID={browser.GetIdentifier()}");
            
            // 浏览器创建完成后，立即调整大小以适应 Panel
            ResizeEmbeddedBrowser(tabPage);
        }

        /// <summary>
        /// 更新地址栏
        /// </summary>
        public void UpdateAddressBar(TabPage tabPage, string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateAddressBar(tabPage, url)));
                return;
            }

            if (tabControl1.SelectedTab == tabPage)
            {
                txtUrl.Text = url;
            }
        }

        /// <summary>
        /// 更新标签页标题
        /// </summary>
        public void UpdateTabTitle(TabPage tabPage, string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTabTitle(tabPage, title)));
                return;
            }

            // 限制标题长度
            if (title.Length > 20)
            {
                title = title.Substring(0, 20) + "...";
            }
            tabPage.Text = title;
        }

        /// <summary>
        /// 更新导航按钮状态
        /// </summary>
        public void UpdateNavigationButtons(TabPage tabPage, bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateNavigationButtons(tabPage, isLoading, canGoBack, canGoForward)));
                return;
            }

            if (tabControl1.SelectedTab == tabPage)
            {
                btnBack.Enabled = canGoBack;
                btnForward.Enabled = canGoForward;
                btnRefresh.Enabled = !isLoading;
            }
        }

        /// <summary>
        /// 更新状态栏
        /// </summary>
        public void UpdateStatus(TabPage tabPage, string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(tabPage, message)));
                return;
            }

            if (tabControl1.SelectedTab == tabPage)
            {
                lblStatus.Text = message;
            }
        }

        #endregion

        #region UI事件处理

        private void btnNewTab_Click(object sender, EventArgs e)
        {
            CreateNewTab();
        }

        private void btnCloseTab_Click(object sender, EventArgs e)
        {
            TabPage currentTab = tabControl1.SelectedTab;
            if (currentTab != null)
            {
                CloseTab(currentTab);
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            string url = txtUrl.Text.Trim();
            if (!string.IsNullOrEmpty(url))
            {
                NavigateToUrl(url);
            }
        }

        private void txtUrl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                btnGo_Click(sender, e);
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            GoBack();
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            GoForward();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshCurrentTab();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 关闭所有浏览器实例
            foreach (var kvp in _tabToUserFlag)
            {
                try
                {
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(kvp.Value);
                    if (browser != null && browser.IsValid)
                    {
                        browser.CloseBrowser(true, true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭浏览器失败: {ex.Message}");
                }
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            // 调整当前标签页的浏览器大小
            TabPage currentTab = tabControl1.SelectedTab;
            if (currentTab != null)
            {
                ResizeEmbeddedBrowser(currentTab);
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 切换标签页时更新地址栏和按钮状态
            TabPage currentTab = tabControl1.SelectedTab;
            if (currentTab != null && _tabToUserFlag.ContainsKey(currentTab))
            {
                string userFlag = _tabToUserFlag[currentTab];
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                
                if (browser != null && browser.IsValid)
                {
                    var mainFrame = browser.GetMainFrame();
                    if (mainFrame != null)
                    {
                        txtUrl.Text = mainFrame.GetURL();
                    }
                }
            }
        }

        #endregion
    }
}

